from flask import Blueprint, request, render_template, flash, abort
from app.models import Article, Tag
from app.constants import PAGE_LIMIT

home_search = Blueprint("home_search", __name__)

@home_search.route("/index")
def index():
    page = request.args.get('page', 1, type=int)
    tid = request.args.get('tid', 0, type=int)
    keywords = request.args.get('keywords', '', type=str)

    article = Article.query.join(Tag, Article.tags)
    if keywords:
        article = article.filter(Article.title.like('%'+keywords+'%'))

    if tid:
        article = article.filter(Tag.id==tid)

    try:
        pagination = article.order_by(Article.id.desc()).paginate(page = page, per_page=PAGE_LIMIT)
    except Exception as e:
        flash(str(e))
        abort(500)

    return render_template("home/search.html",pagination=pagination, keywords=keywords)